import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import 'MyWebView.dart';

typedef void ChangeStatusBarStyle(List<dynamic> args);
typedef void BackToCloseWeb(List<dynamic> args);
typedef Future GetLikeDetails();
typedef Future RequestAddLike();
typedef Future<String?> SaveImageByFlutter(List<dynamic> args);

class JsSDKOptions {
  BuildContext context;
  String userAgent;
  String type;
  String shareTitle;
  String shareDesc;
  String sharePicUrl;
  String shareUrl;
  String articleUrl;
  int publishId;
  int pushId;
  int serviceId;
  String columnId;
  String columnName;

  ChangeStatusBarStyle changeStatusBarStyle;
  BackToCloseWeb backToCloseWeb;
  GetLikeDetails getLikeDetails;
  RequestAddLike requestAddLike;
  SaveImageByFlutter saveImageByFlutter;

  JsSDKOptions({
    required this.context,
    required this.userAgent,
    required this.type,
    required this.shareTitle,
    required this.shareDesc,
    required this.sharePicUrl,
    required this.articleUrl,
    required this.shareUrl,
    required this.publishId,
    required this.pushId,
    required this.serviceId,
    required this.columnId,
    required this.columnName,
    required this.changeStatusBarStyle,
    required this.backToCloseWeb,
    required this.getLikeDetails,
    required this.requestAddLike,
    required this.saveImageByFlutter,
  });
}

class JsSDKFactory {
  static const String PLATFORM_TIANMU = "tianmu";
  static JsSDKFactory? _instance;
  static late JsSDKOptions options;
  static late InAppWebViewController controller;
  static StreamSubscription? _webViewShareSuccessStream;

  JsSDKFactory._internal() {
    _instance = this;
  }

  factory JsSDKFactory() => _instance ?? JsSDKFactory._internal();

  static init(
      InAppWebViewController webViewController, JsSDKOptions jsSDKOptions) {
    controller = webViewController;
    options = jsSDKOptions;
  }

  static dispose() {
    _webViewShareSuccessStream?.cancel();
    _webViewShareSuccessStream = null;
  }

  assembleController() {
    controller.addJavaScriptHandler(
        handlerName: 'jumpToNews',
        callback: (args) async {
          if (args.isNotEmpty) {
            Map map = args[0];
            String? id = '${map['id']}';
            _requestDetilsToJump(int.parse(id));
          } else {
            print("跳转异常，请重试");
          }
        });
  }

  void _requestDetilsToJump(int publishId) {
    Navigator.of(options.context).push(  MaterialPageRoute(builder: (context) => const MyWebView(url: 'https://h5.jcy.jinhua.com.cn/folder1342/folder1343/folder1358/folder1378/folder2467/folder2470/2024-07-03/PwpZ5lG1oBJ2f6Cn.html?v=2',)),);
  }
}
